package com.wei.generator;

import com.wei.utils.ApplicationConstants;
import com.wei.utils.ResourceUtils;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Map;

@Component("mapperGenerator")
public class MapperGenerator implements Generator {

    @Override
    public void GeneratorCode(Map<String, Object> map) {
        Writer writer = null;
        try {

            Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
            configuration.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_28));
            File file = new File(ResourceUtils.getClasspath()+"freemarker");
            configuration.setDirectoryForTemplateLoading(file);

            // 读 mapper
            Template template = configuration.getTemplate("readMapper.flt", "UTF-8");
            String mapperPath = ResourceUtils.getProjectRootPath()+
                    ApplicationConstants.SLASH+
                    map.get("entityPath").toString() +
                    ApplicationConstants.SLASH+
                    map.get("readPackageName").toString().replace('.','/')+
                    ApplicationConstants.SLASH+
                    map.get("readMapperName").toString() +".java";
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mapperPath),"UTF-8"));
            template.process(map,writer);

            // 写 mapper
            template = configuration.getTemplate("writeMapper.flt", "UTF-8");
            mapperPath = ResourceUtils.getProjectRootPath()+
                    ApplicationConstants.SLASH+
                    map.get("entityPath").toString() +
                    ApplicationConstants.SLASH+
                    map.get("writePackageName").toString().replace('.','/')+
                    ApplicationConstants.SLASH+
                    map.get("writeMapperName").toString() +".java";
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mapperPath),"UTF-8"));
            template.process(map,writer);

            writer.flush();
            writer.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
